package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.vo.EmployeeModifyInformationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    EmployeeModifyInformationVO employeeModifyInformationVO;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //接收前端数据进行加密以后与后端数据进行比对
        password=DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {

        //从亲读研传回数据获取数据库所需数据 再使用Mybaits插入数据库

        Employee employee = new Employee();

        //DTO属性拷贝繁琐 可以用BeanUtils
        BeanUtils.copyProperties(employeeDTO,employee);
        //数据库密码加密 默认密码123456
        if (employee.getPassword() ==  null) {
            employee.setPassword("123456");
        }
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));

        //状态 创建时间 更新时间 创建人 更新人
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employee.setCreateUser(BaseContext.getCurrentId());
        //获取创建人ID 可以用已经有的线程工具类 BaseContext.getCurrentId()
         employee.setUpdateUser(BaseContext.getCurrentId());

        //调用Mybatis
        employeeMapper.insert(employee);
    }
    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        //创建List将数据放List中
        List<Employee> records = page.getResult();
        Long total = page.getTotal();

        //返回体 Long total & map records
        return new PageResult(total,records);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
//    @Transactional
    public void update(Integer status, Long id) {
        employeeMapper.update(status,id);
    }

    /**
     * 根据ID查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);

        return employee.builder()
                .createTime(employee.getCreateTime())
                .createUser(employee.getCreateUser())
                .id(employee.getId())
                .idNumber(employee.getIdNumber())
                .name(employee.getName())
                .password(employee.getPassword())
                .phone(employee.getPhone())
                .sex(employee.getSex())
                .status(employee.getStatus())
                .updateTime(employee.getUpdateTime())
                .updateUser(employee.getUpdateUser())
                .username(employee.getUsername())
                .build();
    }
    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void updateMSG(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //前端数据处理
        BeanUtils.copyProperties(employeeDTO,employee);
        //其他数据处理 更新时间 更新人
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateMSG(employee);
    }

}
